package com.febers.ihealth.utils

import java.lang.ref.WeakReference

object Event {

    private val map: MutableMap<String, WeakReference<EventListener>> = HashMap()

    fun register(o: EventListener) {
        if (!map.containsKey(o.toString())) {
            map[o.toString()] = WeakReference(o)
        }
    }

    fun unregister(o: EventListener) {
        if (map.containsKey(o.toString())) {
            map.remove(o.toString())
        }
    }

    fun post(event: Any) {
//        log { "in event start: $event" }
        map.forEach {
            it.value.get()?.onEvent(event)
        }
//        log { "in event finish: $event" }
    }
}

interface EventListener {
    fun onEvent(event: Any, fromParents: Boolean = false)
}